#include "sendthread.h"
#include <QByteArray>

SendThread::SendThread(FakeTcp * socket, QMutex * mutex, QWaitCondition * wait, QList<Packet*> * packets) : socket(socket), packetMutex(mutex), packetWait(wait), packets(packets) {
	stop = false;
}

SendThread::~SendThread() {
	stop = true;
	packetWait->wakeAll();
	ackWait.wakeAll();
	while(isRunning());
}

void SendThread::run() {
	forever { 
		if(stop == true) return;
		packetMutex->lock();
		if(packets->empty()) packetWait->wait(packetMutex); //If there is no packet to send, wait for it.
		if(stop == true) return;

		//Get packet and remove from queue
		Packet* current = packets->at(0);
		packets->removeFirst();
		packetMutex->unlock();
		
		const unsigned int timeout = 30000; //30 seconds timeout

		while(current->hasParts()) { //While packet has not been sent.
			if(stop == true) break;
			QMutex waitMutex;
			waitMutex.lock();
			QByteArray part = current->getPart();
			socket->sendPart(part); //try to send it

			if(ackWait.wait(&waitMutex, timeout) == false) { //if it wasn't succesfull, try again
				bool waitResult = false;

				while(waitResult == false) {
					socket->sendPart(part);
					waitResult = ackWait.wait(&waitMutex, timeout);
				}
			}

			waitMutex.unlock();
		}

		delete current;
	}
}

void SendThread::sendAck() {
	ackWait.wakeAll();
}
